import { defineStore } from "pinia";
import { ref } from 'vue'
import { login } from '@/api/login';
import { useCartStore } from '../index'
import { cartMergeAPI } from '@/api/cart'
// 用户
export const useUserStore = defineStore('user', () => {
  // 定义用户对象
  const userInfo = ref({})

  const cartStore = useCartStore()
  // 调用登录接口
  const getUserInfo = async ({ account, password }) => {
    const res = await login({ account, password })
    userInfo.value = res.result
    // 登录之后获取新的购物车数据
    const newcartlist = cartStore.cartList.map(item => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    })
    await cartMergeAPI(newcartlist)
    cartStore.updataCarlist()
  }
  // 清除信息
  const clearUserInfo = () => {
    userInfo.value = {}
    cartStore.clearCart()
  }
  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }
},
  {
    persist: true
  }
)
